using DeviceCommons.DeviceMessages.Builders;
using DeviceCommons.DeviceMessages.Enums;
using DeviceCommons.DeviceMessages.Serialization;
using DeviceCommons.Security;

namespace DeviceCommons.Examples
{
    /// <summary>
    /// 演示新的加密密码API设计
    /// </summary>
    public class EncryptionPasswordDemo
    {
        public static void RunDemo()
        {
            Console.WriteLine("=== DeviceCommons 加密密码API设计演示 ===\\n");

            // 场景1：使用默认密码加密
            Console.WriteLine("场景1：使用默认密码加密");
            var defaultBuilder = DeviceMessageBuilder.Create()
                .WithHeader(version: 0x02, crcType: CRCTypeEnum.CRC32)
                .WithAesEncryption() // 使用默认密码
                .WithMainDevice("DefaultDevice", 0x01, config =>
                {
                    config.AddReading(100, reading =>
                    {
                        reading.AddState(1, "Default encryption test", StateValueTypeEnum.String);
                    });
                });

            var defaultHex = defaultBuilder.BuildHex(compress: false, encrypt: true);
            Console.WriteLine($"默认加密结果: {defaultHex.Substring(0, 50)}...");
            
            // 使用全局Parser解析（已配置默认解密）
            var globalParser = DeviceCommons.DataHandling.DeviceMessageSerializerProvider.MessagePar;
            var defaultParsed = globalParser.Parser(defaultHex);
            Console.WriteLine($"默认解密成功: {defaultParsed.MainDevice.DID}\\n");

            // 场景2：使用自定义密码加密（新API）
            Console.WriteLine("场景2：使用自定义密码加密（新API）");
            var customBuilder = DeviceMessageBuilder.Create()
                .WithHeader(version: 0x02, crcType: CRCTypeEnum.CRC32)
                .WithMainDevice("CustomDevice", 0x01, config =>
                {
                    config.AddReading(100, reading =>
                    {
                        reading.AddState(1, "Custom encryption test", StateValueTypeEnum.String);
                    });
                });

            // 使用新的API直接传递密码
            var customPassword = "my-secret-password";
            var customHex = customBuilder.BuildHex(compress: false, encrypt: true, encryptionPassword: customPassword);
            Console.WriteLine($"自定义加密结果: {customHex.Substring(0, 50)}...");
            
            // 创建Parser并配置相应的解密函数
            var customParser = new DeviceMessageParser();
            customParser.DecryptFunc = cipherText => new AesEncryptor().Decrypt(cipherText, customPassword);
            var customParsed = customParser.Parser(customHex);
            Console.WriteLine($"自定义解密成功: {customParsed.MainDevice.DID}\\n");

            // 场景3：使用预设加密函数（兼容旧API）
            Console.WriteLine("场景3：使用预设加密函数（兼容旧API）");
            var presetBuilder = DeviceMessageBuilder.Create()
                .WithHeader(version: 0x02, crcType: CRCTypeEnum.CRC32)
                .WithAesEncryption("preset-password") // 预设密码
                .WithMainDevice("PresetDevice", 0x01, config =>
                {
                    config.AddReading(100, reading =>
                    {
                        reading.AddState(1, "Preset encryption test", StateValueTypeEnum.String);
                    });
                });

            var presetHex = presetBuilder.BuildHex(compress: false, encrypt: true);
            Console.WriteLine($"预设加密结果: {presetHex.Substring(0, 50)}...");
            
            // 创建Parser并配置相应的解密函数
            var presetParser = new DeviceMessageParser();
            presetParser.DecryptFunc = cipherText => new AesEncryptor().Decrypt(cipherText, "preset-password");
            var presetParsed = presetParser.Parser(presetHex);
            Console.WriteLine($"预设解密成功: {presetParsed.MainDevice.DID}\\n");

            // 场景4：错误演示 - 密码不匹配
            Console.WriteLine("场景4：错误演示 - 密码不匹配");
            try
            {
                var wrongParser = new DeviceMessageParser();
                wrongParser.DecryptFunc = cipherText => new AesEncryptor().Decrypt(cipherText, "wrong-password");
                wrongParser.Parser(customHex);
            }
            catch (Exception ex)
            {
                Console.WriteLine($"预期错误：{ex.GetType().Name} - {ex.Message.Substring(0, Math.Min(50, ex.Message.Length))}...\\n");
            }

            // 场景5：无解密函数错误演示
            Console.WriteLine("场景5：无解密函数错误演示");
            try
            {
                var noDecryptParser = new DeviceMessageParser();
                // 未配置DecryptFunc
                noDecryptParser.Parser(customHex);
            }
            catch (Exception ex)
            {
                Console.WriteLine($"预期错误：{ex.GetType().Name} - {ex.Message}\\n");
            }

            Console.WriteLine("=== 演示完成 ===");
            Console.WriteLine("总结：");
            Console.WriteLine("1. 默认密码：全局Parser已配置，可直接使用");
            Console.WriteLine("2. 自定义密码：使用新API传递，Parser需相应配置");
            Console.WriteLine("3. 预设密码：兼容旧API，Builder预设加密函数");
            Console.WriteLine("4. 错误处理：密码不匹配或未配置时会抛出明确异常");
        }
    }
}